import React, {
  FC, FunctionComponentElement, Children, CSSProperties,
  cloneElement, createContext, useState,
} from 'react';
import classNames from 'classnames';
import { ITabPaneProps } from './tabPane';

type TabsMode = 'horizontal' | 'vertical';
type TabsType = 'line' | 'card';

/**
 * 向下传递 context 类型
 */
interface ITabsContext {
  activeIndex: string;
  type?: TabsType;
}

/**
 * 传递给子组件的 context
 */
export const TabsContext = createContext<ITabsContext>({ activeIndex: '0' });

export interface ITabsProps {
  /**默认选中激活的项 */
  defaultActiveKey?: string,

  /**样式类名 */
  className?: string;

  /**展示模式 horizontal 横向 vertical 纵向 */
  mode?: TabsMode;

  /**页签的基本样式，可选 line, card 类型 */
  type?: TabsType;

  style?: CSSProperties;

  /**切换面板的回调 */
  onChange?: (activeKey: string) => void;
};

export const Tabs: FC<ITabsProps> = (props) => {
  const {
    className,
    mode,
    style,
    children,
    type,
    defaultActiveKey,
    onChange,
    ...rest
  } = props;

  const [activeKey, setActiveKey] = useState(defaultActiveKey);

  const classes = classNames('tabs', className, {
    'tabs-vertical': mode === 'vertical',
    'tabs-horizontal': mode !== 'vertical',
  });

  /**
   * 子节点点击事件
   * @param key 
   */
  const handChildClick = (key: string) => {
    setActiveKey(key);
    if(onChange && typeof onChange === 'function'){
      onChange(key);
    }
  }

  /**
   * 渲染子节点
   * @returns 
   */
  const renderChildren = () => {
    return Children.map(children, (child) => {
      const childElement = child as FunctionComponentElement<ITabPaneProps>;
      const { displayName } = childElement.type;

      if(displayName !== 'TabPane'){
        console.error('Warning: Tabs has a child which is not a TabPane component');
        return;
      }

      return cloneElement(childElement, {
        onClick: handChildClick,
      });
    });
  };

  /**
   * 绘制内容区
   */
  const renderContentPanel = () => {
    return Children.map(children, (child, index) => {
      const childElement = child as FunctionComponentElement<ITabPaneProps>;
      const { displayName } = childElement.type;

      if(displayName !== 'TabPane'){
        console.error('Warning: Tabs has a child which is not a TabPane component');
        return;
      }

      return (
        <div key={`tabpanel${index}`}>
          {childElement?.props?.children ?? ''}
        </div>
      );
    });
  }

  // 向下层传递的数据
  const contextValue: ITabsContext = {
    activeIndex: activeKey || '0',
    type,
  };

  return (
    <ul
      className={classes}
      style={style}
      {...rest}
    >
      <TabsContext.Provider value={contextValue}>
        <div className="tab-nav-list">{renderChildren()}</div>
        <div className="tab-panel-content">{renderContentPanel()}</div>
      </TabsContext.Provider>
    </ul>
  );
};

Tabs.defaultProps = {
  mode: 'horizontal',
  type: 'line',
};

export default Tabs;